package logic

import (
	"bytes"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/jsonx"
	"strconv"
	"strings"
	"xialou_platform/app/constx"
	"xialou_platform/app/errorx"
	"xialou_platform/app/joinpay/utils"
	"xialou_platform/app/respx"
	"xialou_platform/services/system/rpc/systemClient"
	"xialou_platform/services/wallet/rpc/walletClient"

	"xialou_platform/services/wallet/api/internal/svc"
	"xialou_platform/services/wallet/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PaymentCallbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPaymentCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) PaymentCallbackLogic {
	return PaymentCallbackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PaymentCallbackLogic) PaymentCallback(req *types.PaymentCallbackReq) (resp *types.PaymentCallbackResp, err error) {
	// todo: add your logic here and delete this line
	logx.Infof("汇聚支付回调：%+v", req)

	joinPayMerchantKey, err := l.svcCtx.SystemRpc.SysConfigByKey(l.ctx, &systemClient.KeyReq{Key: constx.JoinPayMerchantKey})
	if err != nil {
		return nil, err
	}
	// 验签
	var respData bytes.Buffer
	respData.WriteString(strconv.Itoa(req.Status))
	respData.WriteString(req.ErrorCode)
	respData.WriteString(req.ErrorCodeDesc)
	respData.WriteString(req.UserNo)
	respData.WriteString(req.TradeMerchantNo)
	respData.WriteString(req.MerchantOrderNo)
	respData.WriteString(req.PlatformSerialNo)
	respData.WriteString(req.ReceiverAccountNoEnc)
	respData.WriteString(req.ReceiverNameEnc)
	respData.WriteString(fmt.Sprintf("%.2f", req.PaidAmount))
	respData.WriteString(fmt.Sprintf("%.2f", req.Fee))
	signResp := utils.SignByMD5(respData.String(), joinPayMerchantKey.ConfigValue)
	logx.Infof("响应结果拼接 --------------------------------->%s", respData.String())
	logx.Infof("响应结果拼接签名 --------------------------------->%s", signResp)
	logx.Infof("响应结果拼接签名 --------------------------------->%s", req.Hmac)
	if signResp != strings.ToUpper(req.Hmac) {
		logx.Info("响应结果验签 --------------------------------->不符合")
		return resp, errorx.NewDefaultError("非法请求～")
	}

	// 状态（0.未处理 1.打款中 2.打款异常 3.已完成）
	var status int64 = 2
	if req.Status == 205 {
		status = 3
	}
	marshal, err := jsonx.Marshal(req)
	if err != nil {
		return nil, err
	}

	_, err = l.svcCtx.WalletRpc.PaymentCallback(l.ctx, &walletClient.PaymentCallbackReq{
		Id:     respx.IDParse(req.MerchantOrderNo).GetInt64(),
		Status: status,
		Remark: string(marshal),
	})
	if err != nil {
		return nil, err
	}
	resp = &types.PaymentCallbackResp{
		StatusCode: "2001",
		Message:    "成功",
	}
	return
}
